package com.comtop.topcloud.device.service.impl;

import com.alibaba.fastjson.JSON;
import com.comtop.topcloud.device.model.influxdb.GatewayUsageModel;
import com.comtop.topcloud.device.model.mysql.DeviceBaseInfo;
import com.comtop.topcloud.device.mapper.DeviceBaseInfoMapper;
import com.comtop.topcloud.device.service.DeviceBaseInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.comtop.topcloud.device.service.redis.RedisCacheService;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;


/**
 * <p>
 * 设备基本信息维护 服务实现类
 * </p>
 *
 * @author 张俊彬
 * @since 2025-01-04
 */
@Service
@AllArgsConstructor
public class DeviceBaseInfoServiceImpl extends ServiceImpl<DeviceBaseInfoMapper, DeviceBaseInfo> implements DeviceBaseInfoService {

    private final RedisCacheService redisCacheService;

    private static final String CACHE_PREFIX = "device_info:";  // 缓存的 key 前缀

    @Override
    public GatewayUsageModel getGatewayUsageModelByDeviceNameAndSerialNumber(String monitorName, String serialNumber) {
        // 从 Redis 中获取数据
        String cacheKey = CACHE_PREFIX + serialNumber+":"+monitorName;
        String cachedData = redisCacheService.getCache(cacheKey);

        // 如果缓存中存在数据，则直接返回
        if (!StringUtils.isEmpty(cachedData)) {
            if ("null".equals(cachedData)) {
                return null;
            }
            return JSON.parseObject(cachedData, GatewayUsageModel.class);
        }

        // 如果缓存中不存在数据，则从数据库查询
        GatewayUsageModel gatewayUsageModel = baseMapper.selectGatewayUsageModelByDeviceNameAndSerialNumber(monitorName, serialNumber);

        // 将查询结果存入缓存，并设置过期时间
        if (gatewayUsageModel != null) {
            redisCacheService.setCache(cacheKey, JSON.toJSONString(gatewayUsageModel), 600);
        } else {
            // 缓存一个空值，防止缓存穿透问题
            redisCacheService.setCache(cacheKey, "null", 300); // 防止缓存穿透
        }

        return gatewayUsageModel;
    }
}
